import { Pool, PoolClient } from 'pg'
import Logger from './logger'
import fs from 'fs'
import path from 'path'
import { parseDbUrl } from './utilsJS'

require('dotenv').config()

const dbConfig = parseDbUrl(process.env.DATABASE_URL)
const pool = new Pool(dbConfig)
const rootpath = process.cwd()
const sqlFilePath = `${rootpath}/prisma/uctoov3InitData.sql`

async function executeSqlFile(filePath: string, client: PoolClient) {
  const fullPath = path.resolve(filePath)
  const sqlContent = fs.readFileSync(fullPath, 'utf-8')
  
  // 分割SQL语句并过滤空行
  const sqlStatements = sqlContent
    .split(';')
    .map(s => s.trim())
    .filter(s => s.length > 0)

  for (const sql of sqlStatements) {
    try {
      await client.query(sql)
      Logger.info(`Executed SQL: ${sql.slice(0, 50)}...`)
    } catch (err) {
      Logger.error(`Error executing SQL: ${sql.slice(0, 50)}...`, err)
      throw err
    }
  }
}

async function initUctooData(databaseName: string, sqlFilePath?: string): Promise<void> {
  let client: PoolClient
  try {
    client = await pool.connect()
    Logger.info('Database connected successfully')

    // 禁用外键约束
    await client.query('SET session_replication_role = replica')

    if (sqlFilePath) {
      await executeSqlFile(sqlFilePath, client)
      Logger.info('SQL file executed successfully')
    }
  } finally {
    // 恢复外键约束
    await client.query('SET session_replication_role = DEFAULT')
    if (client) client.release()
  }
}

// 使用示例
initUctooData(dbConfig.database, sqlFilePath).catch(e => {
  Logger.error('Database initialization failed', e)
  process.exit(1)
})
